package club.caihappy.springsecurity.service.impl;

import club.caihappy.springsecurity.mapper.MenuMapper;
import club.caihappy.springsecurity.mapper.UserMapper;
import club.caihappy.springsecurity.pojo.LoginUser;
import club.caihappy.springsecurity.pojo.User;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

/**
 * Created by Patrick on 2022/9/5
 **/
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private MenuMapper menuMapper;

    @Override
    public UserDetails loadUserByUsername(String name) throws UsernameNotFoundException {
        //获取用户信息
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUserName, name);
        User user = userMapper.selectOne(queryWrapper);
//        System.out.println(user);
        if (Objects.isNull(user)) {
            throw new RuntimeException("用户名或密码错误");
        }

        // TODO: 2022/9/5  获取用户权限
//        List<String> permissions=new ArrayList<>(Arrays.asList("test","admin"));
        List<String> perms = menuMapper.selectPermsByUserId(user.getId());
        return new LoginUser(user, perms);
    }
}
